<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="发货单号" prop="shipmentNo">
        <el-input
          v-model="queryParams.shipmentNo"
          placeholder="请输入发货单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货仓库编号" prop="warehouseId">
        <el-input
          v-model="queryParams.warehouseId"
          placeholder="请输入发货仓库编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入发货仓库名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货类型" prop="shipmentType">
        <el-select
          v-model="queryParams.shipmentType"
          placeholder="请选择发货类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_SHIPMENT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送方式" prop="shippingMethod">
        <el-input
          v-model="queryParams.shippingMethod"
          placeholder="请输入配送方式"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="配送服务" prop="shippingService">
        <el-input
          v-model="queryParams.shippingService"
          placeholder="请输入配送服务"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="承运商代码" prop="carrierCode">
        <el-input
          v-model="queryParams.carrierCode"
          placeholder="请输入承运商代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="承运商名称" prop="carrierName">
        <el-input
          v-model="queryParams.carrierName"
          placeholder="请输入承运商名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="运单号" prop="trackingNo">
        <el-input
          v-model="queryParams.trackingNo"
          placeholder="请输入运单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="跟踪链接" prop="trackingUrl">
        <el-input
          v-model="queryParams.trackingUrl"
          placeholder="请输入跟踪链接"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货总数量" prop="totalQuantity">
        <el-input
          v-model="queryParams.totalQuantity"
          placeholder="请输入发货总数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="总重量" prop="totalWeight">
        <el-input
          v-model="queryParams.totalWeight"
          placeholder="请输入总重量(kg)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="总体积" prop="totalVolume">
        <el-input
          v-model="queryParams.totalVolume"
          placeholder="请输入总体积(立方米)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="包裹数量" prop="packageCount">
        <el-input
          v-model="queryParams.packageCount"
          placeholder="请输入包裹数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="运费" prop="shippingCost">
        <el-input
          v-model="queryParams.shippingCost"
          placeholder="请输入运费"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="保险费" prop="insuranceCost">
        <el-input
          v-model="queryParams.insuranceCost"
          placeholder="请输入保险费"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="处理费" prop="handlingCost">
        <el-input
          v-model="queryParams.handlingCost"
          placeholder="请输入处理费"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="总费用" prop="totalCost">
        <el-input
          v-model="queryParams.totalCost"
          placeholder="请输入总费用"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input
          v-model="queryParams.currencyCode"
          placeholder="请输入货币代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="预计送达日期" prop="estimatedDeliveryDate">
        <el-date-picker
          v-model="queryParams.estimatedDeliveryDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="预计运输天数" prop="estimatedTransitDays">
        <el-input
          v-model="queryParams.estimatedTransitDays"
          placeholder="请输入预计运输天数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货时间" prop="shipTime">
        <el-date-picker
          v-model="queryParams.shipTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="取件时间" prop="pickupTime">
        <el-date-picker
          v-model="queryParams.pickupTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="运输中时间" prop="inTransitTime">
        <el-date-picker
          v-model="queryParams.inTransitTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="派送中时间" prop="outForDeliveryTime">
        <el-date-picker
          v-model="queryParams.outForDeliveryTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="送达时间" prop="deliveryTime">
        <el-date-picker
          v-model="queryParams.deliveryTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="派送尝试次数" prop="deliveryAttempts">
        <el-input
          v-model="queryParams.deliveryAttempts"
          placeholder="请输入派送尝试次数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="配送状态" prop="deliveryStatus">
        <el-select
          v-model="queryParams.deliveryStatus"
          placeholder="请选择配送状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_DELIVERY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签收人" prop="deliverySignature">
        <el-input
          v-model="queryParams.deliverySignature"
          placeholder="请输入签收人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="配送备注" prop="deliveryNotes">
        <el-input
          v-model="queryParams.deliveryNotes"
          placeholder="请输入配送备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="海关申报信息JSON" prop="customsDeclaration">
        <el-input
          v-model="queryParams.customsDeclaration"
          placeholder="请输入海关申报信息JSON"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="清关状态" prop="customsStatus">
        <el-select
          v-model="queryParams.customsStatus"
          placeholder="请选择清关状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMS_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="清关跟踪号" prop="customsTrackingNo">
        <el-input
          v-model="queryParams.customsTrackingNo"
          placeholder="请输入清关跟踪号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否投保" prop="isInsured">
        <el-select
          v-model="queryParams.isInsured"
          placeholder="请选择是否投保"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="保险金额" prop="insuranceAmount">
        <el-input
          v-model="queryParams.insuranceAmount"
          placeholder="请输入保险金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否需要签收" prop="isSignatureRequired">
        <el-select
          v-model="queryParams.isSignatureRequired"
          placeholder="请选择是否需要签收"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="特殊说明" prop="specialInstructions">
        <el-input
          v-model="queryParams.specialInstructions"
          placeholder="请输入特殊说明"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="装箱单URL" prop="packingSlipUrl">
        <el-input
          v-model="queryParams.packingSlipUrl"
          placeholder="请输入装箱单URL"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="运单标签URL" prop="shippingLabelUrl">
        <el-input
          v-model="queryParams.shippingLabelUrl"
          placeholder="请输入运单标签URL"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发票URL" prop="invoiceUrl">
        <el-input
          v-model="queryParams.invoiceUrl"
          placeholder="请输入发票URL"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crossborder:order-shipment:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crossborder:order-shipment:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['crossborder:order-shipment:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="发货编号" align="center" prop="id" />
      <el-table-column label="发货单号" align="center" prop="shipmentNo" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="发货仓库编号" align="center" prop="warehouseId" />
      <el-table-column label="发货仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="发货类型" align="center" prop="shipmentType" />
      <el-table-column label="配送方式" align="center" prop="shippingMethod" />
      <el-table-column label="配送服务" align="center" prop="shippingService" />
      <el-table-column label="承运商代码" align="center" prop="carrierCode" />
      <el-table-column label="承运商名称" align="center" prop="carrierName" />
      <el-table-column label="运单号" align="center" prop="trackingNo" />
      <el-table-column label="跟踪链接" align="center" prop="trackingUrl" />
      <el-table-column label="发货总数量" align="center" prop="totalQuantity" />
      <el-table-column label="总重量(kg)" align="center" prop="totalWeight" />
      <el-table-column label="总体积(m³)" align="center" prop="totalVolume" />
      <el-table-column label="包裹数量" align="center" prop="packageCount" />
      <el-table-column label="运费" align="center" prop="shippingCost" />
      <el-table-column label="保险费" align="center" prop="insuranceCost" />
      <el-table-column label="处理费" align="center" prop="handlingCost" />
      <el-table-column label="总费用" align="center" prop="totalCost" />
      <el-table-column label="货币代码" align="center" prop="currencyCode" />
      <el-table-column label="预计送达日期" align="center" prop="estimatedDeliveryDate" />
      <el-table-column label="预计运输天数" align="center" prop="estimatedTransitDays" />
      <el-table-column
        label="发货时间"
        align="center"
        prop="shipTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="取件时间"
        align="center"
        prop="pickupTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="运输中时间"
        align="center"
        prop="inTransitTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="派送中时间"
        align="center"
        prop="outForDeliveryTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="送达时间"
        align="center"
        prop="deliveryTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="派送尝试次数" align="center" prop="deliveryAttempts" />
      <el-table-column label="配送状态" align="center" prop="deliveryStatus" />
      <el-table-column label="签收人" align="center" prop="deliverySignature" />
      <el-table-column label="配送备注" align="center" prop="deliveryNotes" />
      <el-table-column label="海关申报信息JSON" align="center" prop="customsDeclaration" />
      <el-table-column label="清关状态" align="center" prop="customsStatus" />
      <el-table-column label="清关跟踪号" align="center" prop="customsTrackingNo" />
      <el-table-column label="是否投保" align="center" prop="isInsured" />
      <el-table-column label="保险金额" align="center" prop="insuranceAmount" />
      <el-table-column label="是否需要签收" align="center" prop="isSignatureRequired" />
      <el-table-column label="特殊说明" align="center" prop="specialInstructions" />
      <el-table-column label="装箱单URL" align="center" prop="packingSlipUrl" />
      <el-table-column label="运单标签URL" align="center" prop="shippingLabelUrl" />
      <el-table-column label="发票URL" align="center" prop="invoiceUrl" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crossborder:order-shipment:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crossborder:order-shipment:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderShipmentForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrderShipmentApi, OrderShipment } from '@/api/crossborder/ordershipment'
import OrderShipmentForm from './OrderShipmentForm.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

/** 跨境电商订单发货 列表 */
defineOptions({ name: 'OrderShipment' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<OrderShipment[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  shipmentNo: undefined,
  orderId: undefined,
  orderNo: undefined,
  warehouseId: undefined,
  warehouseName: undefined,
  shipmentType: undefined,
  shippingMethod: undefined,
  shippingService: undefined,
  carrierCode: undefined,
  carrierName: undefined,
  trackingNo: undefined,
  trackingUrl: undefined,
  totalQuantity: undefined,
  totalWeight: undefined,
  totalVolume: undefined,
  packageCount: undefined,
  shippingCost: undefined,
  insuranceCost: undefined,
  handlingCost: undefined,
  totalCost: undefined,
  currencyCode: undefined,
  estimatedDeliveryDate: [],
  estimatedTransitDays: undefined,
  shipTime: [],
  pickupTime: [],
  inTransitTime: [],
  outForDeliveryTime: [],
  deliveryTime: [],
  deliveryAttempts: undefined,
  deliveryStatus: undefined,
  deliverySignature: undefined,
  deliveryNotes: undefined,
  customsDeclaration: undefined,
  customsStatus: undefined,
  customsTrackingNo: undefined,
  isInsured: undefined,
  insuranceAmount: undefined,
  isSignatureRequired: undefined,
  specialInstructions: undefined,
  packingSlipUrl: undefined,
  shippingLabelUrl: undefined,
  invoiceUrl: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderShipmentApi.getOrderShipmentPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderShipmentApi.deleteOrderShipment(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除跨境电商订单发货 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await OrderShipmentApi.deleteOrderShipmentList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: OrderShipment[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderShipmentApi.exportOrderShipment(queryParams)
    download.excel(data, '跨境电商订单发货.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>